# Copyright (c) 2009 by Alex Leone <acleone ~at~ gmail.com>
#
# This file is part of epp.
#
# epp is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# epp is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with epp.  If not, see <http://www.gnu.org/licenses/>.

r"""
Contains the [include] tag.

Syntax:
    [include f="filename1"]
    [include f="filename1" f2="filename2"]

Output:
    Outputs the result of parsing filename.

Examples:
    Note: s[1:] in p.parsetags(s[1:]) is to strip the leading '\n'
          from s

    >>> p = epp.Epp()
    >>> f = open('include_test.txt.epp', 'w')
    >>> f.write('''
    ... ---- include_test.txt.epp ----
    ... [define tag1="hi from 'include_test.txt.epp'!"]
    ... ---- /include_test.txt.epp ----'''[1:])
    >>> f.close()
    >>> s = '''
    ... [ifndef tag1:]
    ...  tag1 hasn't been defined yet!
    ... [include f="include_test.txt.epp"]
    ... [ifdef tag1:]
    ...  tag1 is now defined!'''
    >>> print(p.parsetags(s[1:]))
    tag1 hasn't been defined yet!
    ---- include_test.txt.epp ----
    ---- /include_test.txt.epp ----
    tag1 is now defined!
    >>> os.unlink('include_test.txt.epp')
"""

import os
import epp
import tags
from tags.tag import Tag

tagnames = ["include"]

class Include(Tag):

    def replace(self, eppinst, tagName, attrs):
        """
        Includes a file.
        Returns: the result of parsing the input file
        """
        for attrName, value in attrs:
            input_file = open(value, 'r')
            parser = epp.Epp(eppinst._tags, parent_parser = eppinst)
            output = parser.parsefile(input_file)
            input_file.close()

            return output